/**
 * 版权所有(C)，上海勾芒信息科技，2016，所有权利保留。
 * 
 * 项目名：	carwx
 * 文件名：	TextTemplateTool.java
 * 模块说明：	
 * 修改历史：
 * 2016年11月29日 - Debenson - 创建。
 */
package com.alex.wechat.mp.util;

import java.io.StringReader;
import java.io.StringWriter;
import java.io.Writer;
import java.util.Map;

import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.jeecgframework.core.util.ContextHolderUtils;
import org.jeecgframework.core.util.IpUtil;
import org.jeecgframework.core.util.ResourceUtil;
import org.jeecgframework.web.system.pojo.base.TSDepart;
import org.jeecgframework.web.system.pojo.base.TSUser;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.stereotype.Component;

import com.alex.wechat.mp.config.WxContext;
import com.google.common.collect.Maps;

import freemarker.template.Configuration;
import freemarker.template.Template;

/**
 * 文本模板工具，用来解析微信url等占位符。
 * 
 * @author Debenson
 * @since 0.1
 */
@Component(value = "textTemplateTool")
public class TextTemplateTool implements InitializingBean {
  private static final Logger logger = Logger.getLogger(TextTemplateTool.class);

  private Configuration cfg;

  @Override
  public void afterPropertiesSet() throws Exception {
    final String encoding = "UTF-8";
    cfg = new Configuration();
    cfg.setDefaultEncoding(encoding);
    cfg.setClassForTemplateLoading(getClass(), "");
  }

  /**
   * 解析模板。
   * 
   * @param template
   * @return
   */
  public String resolve(String template) {
    Map<String, Object> model = Maps.newHashMap();

    model.put("org", getSessionUserDepart());
    model.put("user", getSessionUser());
    model.put("wxaccount", WxContext.getWxAccount());
    model.put("wxpublicid", WxContext.getOriginalId());
    model.put("wxopenid", WxContext.getOpenId());
    model.put("domain", IpUtil.getDomain(ContextHolderUtils.getRequest()));

    try {
      Template t = new Template("templateName", new StringReader(template), cfg);
      Writer out = new StringWriter();
      t.process(model, out);
      return out.toString();
    } catch (Exception e) {
      logger.error("", e);
      return template;
    }
  }

  private TSUser getSessionUser() {
    try {
      HttpSession session = ContextHolderUtils.getSession();
      return (TSUser) session.getAttribute(ResourceUtil.LOCAL_CLINET_USER);
    } catch (Exception e) {
      return null;
    }
  }

  private TSDepart getSessionUserDepart() {
    TSUser user = getSessionUser();
    if (user != null) {
      return user.getCurrentDepart();
    } else {
      return null;
    }
  }

}
